home *** CD-ROM | disk | FTP | other *** search
- Path: Rezonet.net!news
- From: ray@ultimate-tech.com (Ray Dunn)
- Newsgroups: comp.lang.c
- Subject: Re: Fastest way to computer log(base2) of x?
- Date: 25 Jan 1996 04:56:53 GMT
- Organization: Ultimate Technographics Inc.
- Message-ID: <4e72il$dvl@ns.RezoNet.NET>
- References: <4e61iu$p6e@villa.fc.net>
- NNTP-Posting-Host: 204.19.230.7
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- In referenced article, Avinash Chopde says...
- >I am trying to find out what could be the fastest way to compute
- >the position of the highest bit in any given integer -- basically, the
- >logarithm to the base 2 of any number.
-
- I can't think of any way faster than a variation of:
-
- /* Returns the Bitnumber of the highest set bit in n.
- Assumes an int is maximum 32-bits long.
- Returns -1 if n == 0
-
- Log2Table is a table filled with the bit-number of the highest bit
- of the numbers 0 through 15
- */
-
- int FindHighestBitNumber(unsigned int n)
- { int i;
- static int Log2Table[16] =
- {-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3};
-
- i = 0;
- if (n > 0xFFFF)
- {
- n = (n >> 16) & 0xFFFF;
- i = 16;
- }
- if (n > 0xFF)
- {
- n = n >> 8;
- i += 8;
- }
- if (n > 0xF)
- {
- n = n >> 4;
- i += 4;
- }
- return(Log2Table[n] + i);
- }
-
- You could also use a union to extract the appropriate byte if speed is
- a concern and shifting is slow on your machine.
-
- If you want more speed, then give a 256 entry Log2Table and remove the
- last conditional.
- --
- Ray Dunn (opinions are my own) | Phone: (514) 938 9050
- Montreal | Phax : (514) 938 5225
- ray@ultimate-tech.com | Home : (514) 630 3749
-
-
-